package com.cby.library.tool.util

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.os.Build
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * 描述信息
 *
 * @author 陈宝阳
 * @create 2020/4/13 15: 57
 */
object AppUtils {

    private const val SHA1 = "SHA1"

    /**
     * 检测当前应用是否在后台
     *
     * @param context Context
     * @return Boolean
     */
    @JvmStatic
    fun isAppIsInBackground(context: Context): Boolean {
        var isInBackground = true
        val am =
            context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            val runningProcesses =
                am.runningAppProcesses
            for (processInfo in runningProcesses) {
                if (processInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (activeProcess in processInfo.pkgList) {
                        if (activeProcess == context.packageName) {
                            isInBackground = false
                        }
                    }
                }
            }
        } else {
            val taskInfo = am.getRunningTasks(1)
            val componentInfo = taskInfo[0].topActivity
            if (componentInfo!!.packageName == context.packageName) {
                isInBackground = false
            }
        }
        return isInBackground
    }

    /**
     * 返回一个签名的对应类型的Sha1字符串
     *
     * @param context
     */
    @JvmStatic
    fun getSignInfo(context: Context): String? {
        val packageName = context.applicationContext.packageName
        val signs = getSignatures(context, packageName)
        return getSignatureString(signs!![0], SHA1)
    }

    /**
     * 返回对应包的签名信息
     *
     * @param context
     * @param packageName
     * @return
     */
    @SuppressLint("PackageManagerGetSignatures")
    private fun getSignatures(context: Context, packageName: String?): Array<Signature>? {
        var packageInfo: PackageInfo?
        try {
            packageInfo = context.packageManager
                .getPackageInfo(packageName!!, PackageManager.GET_SIGNATURES)
            return packageInfo.signatures
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 获取相应的类型的字符串（把签名的byte[]信息转换成16进制）
     *
     * @param sig
     * @param type
     * @return
     */
    private fun getSignatureString(sig: Signature, type: String?): String? {
        val hexBytes = sig.toByteArray()
        var fingerprint = "error!"
        try {
            val digest = MessageDigest.getInstance(type)
            if (digest != null) {
                val digestBytes = digest.digest(hexBytes)
                val sb = StringBuilder()
                for (digestByte in digestBytes) {
                    val i :Int = digestByte.toInt() and 0xFF or 0x100
                    sb.append(Integer.toHexString(i).substring(1, 3))
                }
                fingerprint = sb.toString()
            }
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return fingerprint
    }

    /**
     * 用来判断当前的activity是否是不存在，是否被销毁
     *
     * @param activity
     * @return
     */
    @JvmStatic
    fun isValidActivity(activity: Activity?): Boolean {
        if (activity == null || activity.isFinishing || activity.isDestroyed) {
            return false
        }
        return true
    }

    /**
     * 检测是否安装微信
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun isWeChatAvailable(context: Context): Boolean {
        val packageManager = context.packageManager // 获取PackageManager
        val packageInfo = packageManager.getInstalledPackages(0) // 获取所有已安装程序的包信息
        for (i in packageInfo.indices) {
            val pn = packageInfo[i].packageName
            if (pn == "com.tencent.mm") {
                return true
            }
        }
        return false
    }

    /**
     * 获取当前应用的版本号（versionCode）
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun getAppVersionCode(context: Context): Long {
        return try {
            val manager = context.packageManager
            val info = manager.getPackageInfo(context.packageName, 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                info.longVersionCode
            } else {
                info.versionCode.toLong()
            }
        } catch (var3: Exception) {
            -1
        } catch (e: NoSuchMethodError) {
            -1
        }
    }

    @JvmStatic
    fun getAppName(context: Context): String {
        return try {
            val manager = context.packageManager
            val info = manager.getPackageInfo(context.packageName, 0)

            val name: String = info.applicationInfo.loadLabel(manager).toString()
            CbyLogUtils.flog("name = $name")

            val applicationInfo = manager.getApplicationInfo(context.packageName, 0)
            val name2 = manager.getApplicationLabel(applicationInfo).toString()
            CbyLogUtils.flog("name2 = $name2")

            name
        }catch (e: Exception) {
            ""
        }
    }

    /**
     * 通过包名判断某个应用的版本号（VersionCode）
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun getVersionName(context: Context): String {
        return try {
            val manager = context.packageManager
            val info: PackageInfo = manager.getPackageInfo(context.packageName, 0)
            info.versionName
        }catch (e: Exception) {
            ""
        }
    }

    /**
     * 根据某个包名的应用是否安装
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun isInstalled(context: Context, packageName: String): Boolean {
        val packageManager = context.packageManager // 获取PackageManager
        val packageInfo = packageManager.getInstalledPackages(0) // 获取所有已安装程序的包信息
        for (i in packageInfo.indices) {
            val pn = packageInfo[i].packageName
            if (pn == packageName) {
                return true
            }
        }
        return false
    }

}